//
//  CZPublishViewController.swift
//  sinaSwifWeiBo
//
//  Created by 张雪雪 on 16/3/10.
//  Copyright © 2016年 张雪雪. All rights reserved.
//

import UIKit
import SnapKit

let holderString = "太公在此诸神退位"

class CZPublishViewController: UIViewController , UITextViewDelegate ,UIImagePickerControllerDelegate , UINavigationControllerDelegate{

    
    //需要定义一个成员变量来记录底部的toolBar的约束
    var bottonConstrant:Constraint?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        
        setupTextView()

        // Do any additional setup after loading the view.
        setupToolBar()
        /*
        UIKeyboardWillChangeFrameNotification -- 还没有改变
        UIKeyboardDidChangeFrameNotification -- 已经改变
        */

        //添加键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
        
    }

 //MARK:--设置Nav
    
    private func setupNav() {
    
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
    
        navigationItem.rightBarButtonItem?.enabled = false
        /**
        *  放2个Lable -- 自己试试
        2. 一个lable 实现
        */
        //标题
        let titleLable = UILabel(frame: CGRectMake(0,0,200,44))
        
        titleLable.numberOfLines = 0
        
        titleLable.textAlignment = .Center
        
        
        
        let str = "发布微博\n\(CZUserViewModel.shareInstance.model?.screen_name ?? "")"
        
        let attribute = NSMutableAttributedString(string: str)
        
        //添加属性
        //修改 发布微博 4四个字的属性
        attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(15)], range: NSMakeRange(0, 4))
        //修改 名字 的字
        
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13),NSForegroundColorAttributeName:UIColor.orangeColor()], range: NSMakeRange(4, str.characters.count - 4))
        
    
        titleLable.attributedText = attribute
        
        navigationItem.titleView = titleLable
    }
    
    @objc private func dismiss(){
    
        dismissViewControllerAnimated(true) { () -> Void in
            
        }

    }
    
    @objc private func publish(){
    
    
    
    
    }
    
    
    
    //MARK:--设置-textView
    private func setupTextView(){
    
        /**
        *  添加了一个label --练习一下
        */
    //添加视图
        view.addSubview(textView)
         // 设置约束
        textView.frame = view.frame
        
        //
        textView.holderString = holderString
        
        
        textView.font = UIFont.systemFontOfSize(15)
        
        //实现代理方法
        textView.delegate = self
        //滑动让键盘消失
        textView.alwaysBounceVertical = true
        
        textView.keyboardDismissMode = .OnDrag

     //MARK:-- 添加photoview视图
        textView.addSubview(photoView)
        //设置约束
        photoView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(textView.snp_center)
            
            make.width.equalTo(kUIScreenWidth - 2*CZPhotoViewMargin)
            make.height.equalTo(kUIScreenWidth - 2*CZPhotoViewMargin)
        }
        
        
        
        
    
    }
    
    
    //MARK:--设置底部的toolBar
    
    private func setupToolBar(){
    
    //修改toolBar 的背景颜色
        toolBar.backgroundColor = UIColor.lightGrayColor()
    
        let itemSettings = [["imageName":"compose_toolbar_picture","action":"choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        //定义一个数组,来接受 items
        var items = [UIBarButtonItem]()
        
        for setting in itemSettings{
        
        //自定义button
            
            let button = UIButton(type:UIButtonType.Custom)
        
            //设置button的属性和方法
            button.setImage(UIImage(named: setting["imageName"]!), forState: UIControlState.Normal)
            
            //高亮的
            let imageName = setting["imageName"]!
            
            button.setImage(UIImage(named: "\(imageName)_highlighted"), forState: UIControlState.Highlighted)
            //button的大小一定要设置
            button.sizeToFit()
            //添加方法
            if let action = setting["action"]{
            
            
                button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside);
            
            
            }
            //赋值给UIBarButtonItem
            let item = UIBarButtonItem(customView: button)
            
            // item 添加到toolBar,一定要自己定义一个数组
            items.append(item)
            
            //items添加到toolBar,一定要自己定义一个数组
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        //多的最后一个移除
        items.removeLast()
        
        toolBar.items = items
        
        //添加视图设置约束
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            
            make.height.equalTo(40)

        }
        
    }
    
    
    //MARK:--选择图片的方法
    @objc private func choosePicture(){
    
      print("显示图片")
       //判断一下我们的手机是否能够访问 相册
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
        // 如果可以的话进行页面跳转
            let picker = UIImagePickerController()
            
            picker.sourceType = .PhotoLibrary
            
            //设置代理
            picker.delegate = self
            
           
            
presentViewController(picker, animated: true, completion: { () -> Void in
    
})
        
        
        }
        
    
    }
    
    //MARK:--显示表情
    @objc private func inputEmoticon(){
           print("显示表情")
        /**
        设置一个标志位来剔除 动画对键盘的影响
        */
        //注销第一响应者,然后再让 textView.inPutView 有视图
        textView.resignFirstResponder()
        /*
        当 textView.inputView = nil 可以出现键盘
        当 textView.inputView = 自定义表情视图 弹出我们的表情
        */
        // 当inputView == nil的时候,我们让它显示表情键盘,否则显示系统键盘

        if textView.inputView == nil{
        //
            textView.inputView = emoticonView
        
        
        }else{
        
        textView.inputView = nil
        
        }
        
        
        textView.becomeFirstResponder()
        
    
    }
    
    //MARK:-- 键盘改变通知  改变frame
    func changeToolBarFrame(noti:NSNotification){
    
        if let info = noti.userInfo{
        
        
        //需要把NSRect转换成CGRECT
            let endFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
        
            if endFrame?.origin.y == kUIScreenHeight {
            
            print("退出的时候")
             toolBar.snp_updateConstraints(closure: { (make) -> Void in
                self.bottonConstrant = make.bottom.equalTo(view.snp_bottom).constraint
             })
                
                
                
            }else{
            
            print("弹出的时候")
                //跟新toolBar的frame
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    self.bottonConstrant = make.bottom.equalTo(view.snp_bottom).offset(-endFrame!.size.height).constraint
                })
            
            }
        
        //添加动画 
            let duration = info[UIKeyboardAnimationDurationUserInfoKey]as! NSTimeInterval
            
            UIView.animateWithDuration(duration, animations: { () -> Void in
                self.toolBar.layoutIfNeeded()
            })
            
            
        }

    
    
    }
    
    //一定要记得移除通知
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidChangeFrameNotification, object: nil);
    
    print("控制器 88")
    }
    
    
    //MARK:-- 懒加载
    private lazy var textView: CZTextView = CZTextView()
    
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    private lazy var photoView: CZPhotoView = {
    
     let photo = CZPhotoView()
        weak var weakself = self
    
        photo.closure = {[unowned self] () -> () in
        
        //去调用显示图片的方法
        weakself?.choosePicture()
        
        }
      return photo
    }()
    
    private lazy var emoticonView: CZEmoticonView = {
    let emoticon = CZEmoticonView()
      //设置颜色
        emoticon.backgroundColor = UIColor.yellowColor()
        emoticon.frame.size = CGSizeMake(kUIScreenWidth,216)
        
        
    return emoticon
    }()
    
    
    
    
    
    
 }
//MARK:-- 实现UIImagePicker 的代理方法UIImagePickerControllerDelegate,UINavigationControllerDelegate
extension CZPublishViewController{

    //注意实现了代理方法,一定要调用dismiss 方法，不调用的话，不能自动消失
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //添加图片到图片选择器
        //不建议大家使用属性直接添加
    //建议大家用方法添加
        photoView.addImages(image)
        picker.dismissViewControllerAnimated(true) { () -> Void in
            
        }
        
    }
    
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//        print("消失")
//        picker.dismissViewControllerAnimated(true) { () -> Void in
//            
//            
//        }
//    }



}

extension CZPublishViewController{

    func textViewDidChange(textView: UITextView){
    
    
        if textView.hasText(){
        
        //不显示占位符
            self.textView.holderString = ""
//            self.textView.hidden = true
        
        }else{
        
        //显示占位符
            self.textView.holderString = holderString

        }
    //重绘
        self.textView.setNeedsDisplay()
        
       navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    
    }



}


